package com.szh.es.testcase;


import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 测试使用：聚合使用
 */
public class ESAggrCase {
    public static void main(String[] args) throws IOException {
        // 创建客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200)));

        // 1-聚合测试
        SearchRequest request = new SearchRequest("hotel");
        // 设置size为0，我们不需要看结果

        HashMap<String, List<String>> resultMap = new HashMap<>();
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(20));

        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(20));
        request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(20));

        SearchResponse searchResponse = esClient.search(request, RequestOptions.DEFAULT);

        // 获取结果
        Aggregations aggregations = searchResponse.getAggregations();

        resultMap.put("品牌",getAgg(aggregations, "brandAgg"));
        resultMap.put("城市",getAgg(aggregations, "cityAgg"));
        resultMap.put("星级",getAgg(aggregations, "starAgg"));

        System.out.println(resultMap);
        esClient.close();
    }

    private static List<String> getAgg(Aggregations aggregations, String aggName) {
        Terms brandAgg = aggregations.get(aggName);

        ArrayList<String> list = new ArrayList<>();
        brandAgg.getBuckets().forEach(b->{
            String keyAsString = b.getKeyAsString();
            list.add(keyAsString);
        });
        return list;
    }
}

